﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

public partial class start_learn_frame : System.Web.UI.Page
{

    public imsitemHierList mobjimsitemHierList
    {
        get
        {
            if (ViewState["mobjimsitemHierList"] == null)
                ViewState["mobjimsitemHierList"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjimsitemHierList"].ToString()] as imsitemHierList;


        }
        set
        {
            if (ViewState["mobjimsitemHierList"] == null)
                ViewState["mobjimsitemHierList"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mobjimsitemHierList"].ToString()] = value;
        }
    }


    public RegisteredCourses mobjRegisteredCourses
    {
        get
        {
            if (ViewState["mobjRegisteredCourses"] == null)
                ViewState["mobjRegisteredCourses"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mobjRegisteredCourses"].ToString()] as RegisteredCourses;

        }
        set
        {
            if (ViewState["mobjRegisteredCourses"] == null)
                ViewState["mobjRegisteredCourses"] = System.Guid.NewGuid().ToString();

           Session[ViewState["mobjRegisteredCourses"].ToString()] = value;
        }
    }
    
    
    
    public Courses mObjCourses
    {
        get
        {
            if (ViewState["mObjCourses"] == null)
                ViewState["mObjCourses"] = System.Guid.NewGuid().ToString();

            return Session[ViewState["mObjCourses"].ToString()] as Courses;


        }
        set
        {
            if (ViewState["mObjCourses"] == null)
                ViewState["mObjCourses"] = System.Guid.NewGuid().ToString();

            Session[ViewState["mObjCourses"].ToString()] = value;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

            //setHeight
            ClientScript.RegisterStartupScript(Page.GetType(), "setHeight", "setHeight();", true);


            CheckSecurityAndCustomizePage();


            CheckCourseAndItsFiles();


            Page.DataBind();


            GlobalVars.addLog(mobjRegisteredCourses.ID, 6);
        }
        else
        {
            tv1_SelectedNodeChanged1(sender, e);
        }

    }


    /// <summary>
    /// this function will check the security of that page
    /// </summary>
    private void CheckSecurityAndCustomizePage()
    {
        Persons currentPerson = GlobalVars.getCurrentPerson();

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Registered_courses_page))
        {
            Response.Redirect("LoginEN.aspx");
        }

        Courses courseNew = new Courses();
        try { courseNew.ID = long.Parse(Request["ID"]); }
        catch { Response.Redirect("LoginEN.aspx"); }

        if (!currentPerson.lstCourses.Contains(courseNew))
        {
            Response.Redirect("LoginEN.aspx");
        }


        try { mobjRegisteredCourses = (from reg in currentPerson.lstRegisteredCourses where reg.CoursesID == courseNew.ID select reg).ElementAt(0); }
        catch { Response.Redirect("LoginEN.aspx"); }

    }


    /// <summary>
    /// this function will check the request for the course id and be sure that there is a course with that id
    /// </summary>
    private void CheckCourseAndItsFiles()
    {
        if (Request["ID"] == null)
        {
            Response.Redirect("loginEN.aspx");

        }

        long CourseID = -1;
        try { CourseID = long.Parse(Request["ID"]); }
        catch { Response.Redirect("loginEN.aspx"); }

        CoursesDB objCoursesDB = new CoursesDB(ConnectionStrings.LMS);

        List<Courses> lstCourses = objCoursesDB.getCoursesByID(CourseID);

        if (lstCourses.Count == 0)
        {
            Response.Redirect("loginEN.aspx");
        }


        buildCourseDir(lstCourses[0]);



    }





    /// <summary>
    /// this function will build the directory and get the toc
    /// </summary>
    /// <param name="objCourses">the course to build its directory and get its toc</param>
    private void buildCourseDir(Courses objCourses)
    {
        mObjCourses = objCourses;

        Title = mObjCourses.CourseNameEN;

        string strXmlName = GlobalVars.getCoursePath(objCourses) + "imsmanifest.xml";


        if (!File.Exists(strXmlName))
        {
            try
            {
                if (!Directory.Exists(GlobalVars.getCoursePath(objCourses)))
                    Directory.CreateDirectory(GlobalVars.getCoursePath(objCourses));

                FastZip fz = new FastZip();
                fz.ExtractZip(Server.MapPath("./CoursesFiles/" + objCourses.Path), GlobalVars.getCoursePath(objCourses), "");
            }
            catch
            {

            }
        }


        if (!File.Exists(strXmlName))
        {
            Response.Redirect("LoginEN.aspx");
            return;
        }


        List<imsitem> lstNew = imsitem.getListOfFile(strXmlName);

        CreateScoes(lstNew);
        
        mobjimsitemHierList = new imsitemHierList(lstNew);

        


        tv1.DataSource = mobjimsitemHierList;

        

        tv1.DataBind();


        


        bool isOne = false;

        string strLastIn = "";
        isOne = getIfListIsOne(lstNew,ref strLastIn);


        if (isOne)
        {


            ClientScript.RegisterStartupScript(Page.GetType(), "hide", "hideit();", true);

            ClientScript.RegisterStartupScript(Page.GetType(), "img", "hideImgShow();", true);

            



        }


        
        string url = "";


        if (lstNew.Count > 0)
        {
            url = getFirstUrlChild(lstNew[0]);
        }

        if (url != "")
        {
            url = GlobalVars.getCourseVirtualPath(mObjCourses) + url;
        }

        try
        {

            string strLastPagePath = Server.MapPath(mobjRegisteredCourses.CurrentData);
            string strMainCourseFolder = GlobalVars.getCoursePath(mObjCourses);

            if (File.Exists(strLastPagePath) && strLastPagePath.ToLower().Contains(strMainCourseFolder.ToLower()))
            {
            
                    _MainFrame.Attributes["src"] = mobjRegisteredCourses.CurrentData;
            
            

            }
            else
            {
                _MainFrame.Attributes["src"] = url;
            }
        }
        catch
        {
            _MainFrame.Attributes["src"] = url;
        }


        

        

        List<CoursesScoes> lstSocID = new List<CoursesScoes>(from obj in mobjRegisteredCourses.lstCoursesScoes where obj.ScoName == _MainFrame.Attributes["src"] select obj );

        if (lstSocID.Count == 0)
        {
            CoursesScoesDB objCoursesScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);
            CoursesScoes objCoursesScoes = new CoursesScoes();
            objCoursesScoes.RegisteredCoursesID = mobjRegisteredCourses.ID;
            objCoursesScoes.IsCompleted = false;
            objCoursesScoes.ScoName = _MainFrame.Attributes["src"];

            objCoursesScoesDB.Insert(objCoursesScoes);
        }

         lstSocID = new List<CoursesScoes>(from obj in mobjRegisteredCourses.lstCoursesScoes where obj.ScoName == _MainFrame.Attributes["src"] select obj);

        if (lstSocID.Count == 0)
            Response.Redirect("./LoginEN.aspx");



        RegisteredCoursesDB objRegisteredCoursesDB = new RegisteredCoursesDB(ConnectionStrings.LMS);
        List<RegisteredCourses> lstNewRegistered = objRegisteredCoursesDB.getRegisteredCoursesByID(mobjRegisteredCourses.ID);
        if (lstNewRegistered.Count == 0)
            Response.Redirect("./LoginEN.aspx");

        lstNewRegistered[0].CurrentData = _MainFrame.Attributes["src"];

        objRegisteredCoursesDB.Update(lstNewRegistered[0]);

       
        
        //frameToc.Attributes["src"] = "./toc.aspx?ID=" + mObjCourses.ID.ToString();





        ClientScript.RegisterStartupScript(Page.GetType(), "strSetID", "RegisteredCourses.ScoID = " + lstSocID[0].ID.ToString() + " ; API = new LMSAPI_1484_11(); API.MyData.deserialize('" + lstSocID[0].ScoData.Replace("'", "\\'") + "') ; ", true);




    }



    /// <summary>
    /// this function will create scoes for all pages
    /// </summary>
    /// <param name="lstNew">a list of item to create its data</param>
    private void CreateScoes(List<imsitem> lstNew)
    {

        foreach (imsitem imsNew in lstNew)
        {
            if (imsNew.href != "" && imsNew.href != "#")
            {
                CreateScoes(imsNew);
            }

            if (imsNew.childs != null)
            {
                CreateScoes(imsNew.childs);
            }
        }



    }


    /// <summary>
    /// this function will create it for one page
    /// </summary>
    /// <param name="imsNew">the page data</param>
    private void CreateScoes(imsitem imsNew)
    {
        string url = imsNew.href;
        

        if (url == "")
            return;

        url = GlobalVars.getCourseVirtualPath(mObjCourses) + url;



        List<CoursesScoes> lstSocID = new List<CoursesScoes>(from obj in mobjRegisteredCourses.lstCoursesScoes where obj.ScoName == url select obj);

        if (lstSocID.Count == 0)
        {
            CoursesScoesDB objCoursesScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);
            CoursesScoes objCoursesScoes = new CoursesScoes();
            objCoursesScoes.RegisteredCoursesID = mobjRegisteredCourses.ID;
            objCoursesScoes.IsCompleted = false;
            objCoursesScoes.ScoName = url;
            objCoursesScoesDB.Insert(objCoursesScoes);
        }
        else
        {
            if (lstSocID[0].IsCompleted)
            {
                string strHtml = "<span style=\"font-size:10px;color:Red;font-weight:bold;\">√</span>";

                if (imsNew.title.Length > strHtml.Length &&  imsNew.title.Substring(imsNew.title.Length - strHtml.Length) != strHtml)
                {
                    imsNew.title = imsNew.title + "&nbsp;&nbsp;&nbsp;&nbsp;" + strHtml;
                }
                else if (imsNew.title.Length <= strHtml.Length)
                {
                    imsNew.title = imsNew.title + "&nbsp;&nbsp;&nbsp;&nbsp;" + strHtml;
                }

            }
        }
    }


    /// <summary>
    /// this function will get if it's only one or not
    /// </summary>
    /// <param name="lstNew">the list containing childs</param>
    /// <param name="strLast">this will have the last href it founds</param>
    /// <returns>boolean value</returns>
    private bool getIfListIsOne(List<imsitem> lstNew,ref string strLast)
    {
        if (lstNew == null)
            return true;
        

        foreach (imsitem obj in lstNew)
        {
            if (strLast == "")
            {
                strLast = obj.objResource.href;
            }
            else
            {
                if (obj.objResource.href != "" && obj.objResource.href != strLast)
                {
                    return false;

                }


                
            }


            if (!getIfListIsOne(obj.childs, ref strLast))
                return false;

        }

        return true;

    }



    /// <summary>
    /// this function will get the first child url recursive
    /// </summary>
    /// <param name="imsitem">the item to get its child url</param>
    /// <returns>the url returned</returns>
    private string getFirstUrlChild(imsitem imsitem)
    {
        if (imsitem.href != "")
            return imsitem.href;

        foreach (imsitem child in imsitem.childs)
        {
            string url = getFirstUrlChild(child);
            if (url != "")
                return url;
        }

        return "";

    }





    protected void tv1_SelectedNodeChanged1(object sender, EventArgs e)
    {


        imsitemHier item = getItemFromHier(mobjimsitemHierList, tv1.SelectedNode.Value);

        List<imsitem> lstNew = new List<imsitem>();

        foreach (imsitemHier obj in mobjimsitemHierList)
        {
            lstNew.Add(obj.objImsitem);
        }

        CreateScoes(lstNew);

        mobjimsitemHierList = new imsitemHierList(lstNew);




        tv1.DataSource = mobjimsitemHierList;



        tv1.DataBind();



        if (item == null)
            return;

        string url = "";
        if (item.href == "")
        {
            url = setUrlOfNodes(item);

        }
        else
            url = item.href;

        if (url == "")
            return;

        url = GlobalVars.getCourseVirtualPath(mObjCourses) + url;



        List<CoursesScoes> lstSocID = new List<CoursesScoes>(from obj in mobjRegisteredCourses.lstCoursesScoes where obj.ScoName == url select obj);

        if (lstSocID.Count == 0)
        {
            CoursesScoesDB objCoursesScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);
            CoursesScoes objCoursesScoes = new CoursesScoes();
            objCoursesScoes.RegisteredCoursesID = mobjRegisteredCourses.ID;
            objCoursesScoes.IsCompleted = false;
            objCoursesScoes.ScoName = url;
            objCoursesScoesDB.Insert(objCoursesScoes);
        }

        lstSocID = new List<CoursesScoes>(from obj in mobjRegisteredCourses.lstCoursesScoes where obj.ScoName == url select obj);

        if (lstSocID.Count == 0)
            return;



        RegisteredCoursesDB objRegisteredCoursesDB = new RegisteredCoursesDB(ConnectionStrings.LMS);
        List<RegisteredCourses> lstNewRegistered = objRegisteredCoursesDB.getRegisteredCoursesByID(mobjRegisteredCourses.ID);
        if (lstNewRegistered.Count == 0)
            return;

        lstNewRegistered[0].CurrentData = url;

        objRegisteredCoursesDB.Update(lstNewRegistered[0]);



        _MainFrame.Attributes["src"] = url;


        ClientScript.RegisterStartupScript(Page.GetType(), "strSetID", "RegisteredCourses.ScoID = " + lstSocID[0].ID.ToString() + " ; API = new LMSAPI_1484_11(); API.MyData.deserialize ('" + lstSocID[0].ScoData.Replace("'", "\\'") + "') ;  ", true);
    }


    /// <summary>
    /// this function will search for an item by its id
    /// </summary>
    /// <param name="lst">the list to search in</param>
    /// <param name="p">the id to search for</param>
    /// <returns>the item have the id</returns>
    private imsitemHier getItemFromHier(imsitemHierList lst, string p)
    {
        for (int i = 0; i < lst.Count; i++)
        {
            imsitemHier item = (imsitemHier)lst[i];
            if (item.id == p)
                return item;
            else
            {
                if (item.childs != null)
                {
                    imsitemHier itemNew = getItemFromHier(new imsitemHierList(item.childs), p);

                    if (itemNew != null)
                        return itemNew;
                }
            }
        }


        return null;
    }


    /// <summary>
    /// this function will set the url of nodes recursive
    /// </summary>
    /// <param name="MyNode">the node to start with</param>
    protected string setUrlOfNodes(imsitemHier MyNode)
    {
        string value = "";
        if (MyNode.href == "")
        {
            value = getFirstNavigateUrl(MyNode);



        }
        else
            value = MyNode.href;


        return value;

    }



   




    /// <summary>
    /// this function will get the first child have navigateurl and return the url
    /// </summary>
    /// <param name="tn">the parent node</param>
    /// <returns>the navigate url of first child have one</returns>
    public string getFirstNavigateUrl(imsitemHier tn)
    {
        if (tn.href != "")
            return tn.href;
        foreach (imsitemHier tin in new imsitemHierList( tn.childs))
        {
            string navigate = getFirstNavigateUrl(tin);
            if (navigate != "")
                return navigate;
        }

        return "";
    }

    
}